package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import com.exercise.AndroidCamera.PostListActivity.readPostListAsync;

import android.R.integer;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.os.Build;
/*
기능 : 포스트를 읽을 수 있음
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class ReadPostActivity extends BaseActivity implements
		View.OnTouchListener, OnMenuItemClickListener {

	Intent mIntent;
	String userID;

	private ViewFlipper flipper;
	ImageView image;
	private LinearLayout.LayoutParams params;

	private float xDown;
	private float xUp;

	// When flag and like are 0, it is default. It means that these's not
	// comment window and don't push the like button.
	int flag = 0;
	private int like = 0;

	ArrayList<String> titleArray;
	ArrayList<String> dateArray;
	ArrayList<String> textArray;
	ArrayList<String> editorArray;
	ArrayList<String> likeArray;
	ArrayList<String> photoNumArray;
	ArrayList<String> commentNumArray;

	ArrayList<String> baseArray;
	ArrayList<Bitmap> bitmapArray;

	ArrayList<String> c_userArray;
	ArrayList<String> c_commentArray;
	ArrayList<String> c_idArray;

	CommentReadAsync commentRead = new CommentReadAsync();;

	ListView list;
	CommentAdapter adapter;

	TextView txtComment;

	private String board_id;

	private String likeFlag="false";
	private ProgressDialog waitDialog;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_read_post);

		userID = getIntent().getExtras().getString("userID");
		board_id = getIntent().getExtras().getString("board_id");

		titleArray = new ArrayList<String>();
		dateArray = new ArrayList<String>();
		textArray = new ArrayList<String>();
		editorArray = new ArrayList<String>();
		likeArray = new ArrayList<String>();
		photoNumArray = new ArrayList<String>();
		commentNumArray = new ArrayList<String>();

		baseArray = new ArrayList<String>();

		c_userArray = new ArrayList<String>();
		c_commentArray = new ArrayList<String>();
		c_idArray = new ArrayList<String>();

		txtComment = (TextView) findViewById(R.id.editcomment);

		flipper = (ViewFlipper) findViewById(R.id.viewFilpper);
		flipper.setOnTouchListener(this);
		params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);

		Intent mIntent = getIntent();

		readPostAsync readPost = new readPostAsync();
		readPost.execute();


		getActionBar().setDisplayHomeAsUpEnabled(true);

		Button btnComment = (Button) findViewById(R.id.btncomment);

		btnComment.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				CommentWriteAsync commentWrite = new CommentWriteAsync();
				commentWrite.execute();

				clear();
				onResume();

				EditText editComment = (EditText) findViewById(R.id.editcomment);
				editComment.setText("");

			}
		});

		
		getActionBar().setDisplayShowHomeEnabled(false);
		

	}

	public void onResume() {
		if (flag == 1) {
			CommentReadAsync readComment = new CommentReadAsync();
			readComment.execute();
			invalidateOptionsMenu();
			findViewById(R.id.commentlayout).setVisibility(View.VISIBLE);
			findViewById(R.id.readlayout).setVisibility(View.GONE);
		}

		super.onResume();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (v != flipper) {
			return false;
		}

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				xDown = event.getX();
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				xUp = event.getX();
	
				if (xUp + 50 < xDown) {
					flipper.setInAnimation(AnimationUtils.loadAnimation(this,
							R.anim.push_left_in));
					flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
							R.anim.push_left_out));
					flipper.showNext();
				} else if (xUp > xDown + 50) {
					flipper.setInAnimation(AnimationUtils.loadAnimation(this,
							R.anim.push_right_in));
					flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
							R.anim.push_right_out));
					flipper.showPrevious();
				}
			}

		return true;
	}

	TextView tv;
	MenuItem item;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.

		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.read_post, menu);

		RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.likes)
				.getActionView();
		tv = (TextView) badgeLayout
				.findViewById(R.id.actionbar_notifcation_likes);

		final Menu m = menu;
		item = menu.findItem(R.id.likes);
		MenuItemCompat.getActionView(item).findViewById(R.id.btnImageLikes)
				.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Log.d("likes", "skdhk!");
						onOptionsItemSelected(item);
					}
				});

		if (likeFlag.equals("true")) {
			like = 1;
			menu.findItem(R.id.likes).setIcon(R.drawable.pushlikes);
			MenuItemCompat.getActionView(item).findViewById(R.id.btnImageLikes)
					.setBackgroundResource(R.drawable.pushlikes);

		} else {
			menu.findItem(R.id.likes).setIcon(R.drawable.likes);
			MenuItemCompat.getActionView(item).findViewById(R.id.btnImageLikes)
					.setBackgroundResource(R.drawable.likes);
		}

		return true;
	}

	public boolean onPrepareOptionsMenu(Menu menu) {
		if (flag != 0) {
			if (menu.findItem(R.id.likes) != null) {
				menu.findItem(R.id.likes).setVisible(false);
			} else {
				menu.findItem(R.id.likes).setVisible(true);
			}
		}

		if (like == 1) {
			menu.findItem(R.id.likes).setIcon(R.drawable.pushlikes);
			MenuItemCompat.getActionView(item).findViewById(R.id.btnImageLikes)
					.setBackgroundResource(R.drawable.pushlikes);
		} else if (like == 0) {
			if (likeFlag.equals("true")) {
				like = 1;
				likeFlag = "false";
				menu.findItem(R.id.likes).setIcon(R.drawable.pushlikes);
				MenuItemCompat.getActionView(item)
						.findViewById(R.id.btnImageLikes)
						.setBackgroundResource(R.drawable.pushlikes);
			} else {
				menu.findItem(R.id.likes).setIcon(R.drawable.likes);
				MenuItemCompat.getActionView(item)
						.findViewById(R.id.btnImageLikes)
						.setBackgroundResource(R.drawable.likes);
			}
		}

		if (!likeArray.isEmpty()) {
			tv.setText(likeArray.get(0));
		}
		
		if (!editorArray.isEmpty()){
			if(editorArray.get(0).toString().equals(userID))
				menu.findItem(R.id.read_delete).setVisible(true);
		}

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		String text = null;

		Log.d("tag", " " + item.getItemId());
		switch (item.getItemId()) {
		case android.R.id.home:
			if (flag != 0) {
				flag = 0;
				clear();
				invalidateOptionsMenu();
				findViewById(R.id.commentlayout).setVisibility(View.GONE);
				findViewById(R.id.readlayout).setVisibility(View.VISIBLE);
			} else
				finish();
			break;
			
		case R.id.read_delete : // AsyncTask 돌려야해
			deleteBoardAsync deleteBoard = new deleteBoardAsync();
			deleteBoard.execute();
			break;

		case R.id.likes:
			if (like == 0) {
				LikePostAsync likePost = new LikePostAsync();
				likePost.execute();
				like = 1;
			} else {
				UnlikePostAsync unlikePost = new UnlikePostAsync();
				unlikePost.execute();
				likeFlag = "false";
				like = 0;
			}
			likeArray.clear();
			readPostAsync readAsync = new readPostAsync();
			readAsync.execute();
			break;

		default:
			return false;
		}
		return true;
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_read_post,
					container, false);
			return rootView;
		}
	}

	public void onBackPressed() {
		if (flag == 0) {
			finish();
		} else {
			flag = 0;
			clear();
			findViewById(R.id.commentlayout).setVisibility(View.GONE);
			findViewById(R.id.readlayout).setVisibility(View.VISIBLE);
			commentNumArray.clear();
			readPostAsync readAsyn = new readPostAsync();
			readAsyn.execute();
		}
	}

	protected String[] read_post(Context context, String location_id) {
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		String[] result = new String[2];
		result[0] = "error"; // JSON flag
		result[1] = null; // message

		try {
			StringBuilder builder = new StringBuilder();

			URL url = new URL("http://54.199.194.197/read_post.php");
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				conn.setConnectTimeout(150000); 
				conn.setReadTimeout(150000);
				conn.setDefaultUseCaches(false); 
				conn.setDoInput(true); 
										
				conn.setDoOutput(true); 
				conn.setRequestMethod("POST"); 
				conn.setRequestProperty("content-type",
						"application/x-www-form-urlencoded"); 

				StringBuffer buffer = new StringBuffer();
				buffer.append("board_id").append("=").append(board_id);
				Log.d("board id", buffer.toString());

				OutputStreamWriter outStream = new OutputStreamWriter(
						conn.getOutputStream(), "UTF-8");
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();

				InputStreamReader inputStream = new InputStreamReader(
						conn.getInputStream(), "UTF-8");
				br = new BufferedReader(inputStream);

				String line;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}

				br.close();

				pString = builder.toString();
				Log.d("pString in read post", pString);

				JSONObject jObject = new JSONObject(pString);
				JSONArray editorObject = new JSONArray(
						jObject.getString("editor"));
				JSONArray titleObject = new JSONArray(
						jObject.getString("title"));
				JSONArray dateObject = new JSONArray(jObject.getString("date"));
				JSONArray textObject = new JSONArray(jObject.getString("text"));
				JSONArray likeObject = new JSONArray(
						jObject.getString("like_board"));
				JSONArray photoNumObject = new JSONArray(
						jObject.getString("photo_num"));
				JSONArray commentNumObject = new JSONArray(
						jObject.getString("comment_num"));

				editorArray.add(editorObject.getString(0));
				titleArray.add(titleObject.getString(0));
				dateArray.add(dateObject.getString(0));
				textArray.add(textObject.getString(0));
				likeArray.add(likeObject.getString(0));
				photoNumArray.add(photoNumObject.getString(0));
				commentNumArray.add(commentNumObject.getString(0));
			} else {

				throw new Exception("network error");
			}

		} catch (SocketTimeoutException se) {

			result[1] = "network error";

		} catch (Exception e) {

			result[1] = e.getMessage();

		} finally {

			if (conn != null)
				conn.disconnect();

			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
			}
		}
		return result;
	}

	public class readPostAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			waitDialog = new ProgressDialog(ReadPostActivity.this, R.style.MyProgressTheme);
			waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			waitDialog.setMessage("게시물을 읽고 있습니다...");
			waitDialog.setIcon(R.id.icon);
			waitDialog.setIndeterminate(true);
			waitDialog.setCancelable(true);
			waitDialog.show();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			read_post(ReadPostActivity.this, "0");
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			
			ConfirmLikePostAsync confirmlike = new ConfirmLikePostAsync();
			confirmlike.execute();
			invalidateOptionsMenu();
			TextView tv = (TextView) findViewById(R.id.textView);
			tv.setText(textArray.get(0));
			TextView dateView = (TextView) findViewById(R.id.dateText);
			TextView writerView = (TextView) findViewById(R.id.writerText);
			Button commentBtn = (Button) findViewById(R.id.commentBtn);
			dateView.setText("올린날짜: " + dateArray.get(0));
			writerView.setText("올린사람: " + editorArray.get(0));
			commentBtn.setText("댓글 남기기[" + commentNumArray.get(0) + "]");
		
			commentBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (flag == 0) {
						flag = 1;
						CommentReadAsync readComment = new CommentReadAsync();
						readComment.execute();
						invalidateOptionsMenu();
						findViewById(R.id.commentlayout).setVisibility(
								View.VISIBLE);
						findViewById(R.id.readlayout).setVisibility(View.GONE);
					}
				}
			});

			getActionBar().setTitle(titleArray.get(0));
			if (photoNumArray.get(0).equals("0"))
				;
			else {
				flipper.setVisibility(View.VISIBLE);
				imagePostAsync imgPostAsync = new imagePostAsync();
				imgPostAsync.execute();
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	public void makeBitmap() {
		bitmapArray = new ArrayList<Bitmap>();
		for (int i = 0; i < baseArray.size(); i++) {
			byte[] decodeByte = Base64.decode(baseArray.get(i), Base64.NO_WRAP);
			Bitmap decodeBitmap = BitmapFactory.decodeByteArray(decodeByte, 0,
					decodeByte.length);
			bitmapArray.add(decodeBitmap);
		}
		baseArray.clear();
	}

	protected String[] image_read(Context context, String location_id) {
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		String[] result = new String[2];
		result[0] = "error"; // JSON flag
		result[1] = null; // message

		try {
			StringBuilder builder = new StringBuilder();

			URL url = new URL("http://54.199.194.197/read_post_image.php");
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				conn.setConnectTimeout(150000); 
				conn.setReadTimeout(150000);
				conn.setDefaultUseCaches(false); 
				conn.setDoInput(true); 
				conn.setDoOutput(true); 
				conn.setRequestMethod("POST"); 
				conn.setRequestProperty("content-type",
						"application/x-www-form-urlencoded"); 
				StringBuffer buffer = new StringBuffer();
				buffer.append("board_id").append("=").append(board_id);
				Log.d("board id", buffer.toString());

				OutputStreamWriter outStream = new OutputStreamWriter(
						conn.getOutputStream(), "UTF-8");
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();

				InputStreamReader inputStream = new InputStreamReader(
						conn.getInputStream(), "UTF-8");
				br = new BufferedReader(inputStream);

				String line;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}

				br.close();

				pString = builder.toString();
				JSONObject jObject = new JSONObject(pString);
				JSONArray baseObject = new JSONArray(jObject.getString("base"));

				for (int i = 0; i < baseObject.length(); i++) {
					baseArray.add(baseObject.getString(i));
				}

			} else {

				throw new Exception("network error");
			}

		} catch (SocketTimeoutException se) {

			result[1] = "network error";

		} catch (Exception e) {

			result[1] = e.getMessage();

		} finally {

			if (conn != null)
				conn.disconnect();

			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
			}
		}
		return result;
	}

	public class imagePostAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			image_read(ReadPostActivity.this, "0");
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			makeBitmap();

			for (int i = 0; i < bitmapArray.size(); i++) {
				image = new ImageView(ReadPostActivity.this);
				image.setLayoutParams(params);
				image.setImageBitmap(bitmapArray.get(i));
				flipper.addView(image);
			}
			bitmapArray.clear();

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	// comment
	protected String[] comment_read(Context context) {
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		String[] result = new String[2];
		result[0] = "error"; // JSON flag
		result[1] = null; // message

		try {
			StringBuilder builder = new StringBuilder();

			URL url = new URL("http://54.199.194.197/read_comment.php");
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				conn.setConnectTimeout(150000); 
				conn.setReadTimeout(150000);
				conn.setDefaultUseCaches(false); 
				conn.setDoInput(true); 
				conn.setDoOutput(true); 
				conn.setRequestMethod("POST"); 
				conn.setRequestProperty("content-type",
						"application/x-www-form-urlencoded"); 
				StringBuffer buffer = new StringBuffer();
				buffer.append("board_id").append("=").append(board_id);
				Log.d("board id_comment", buffer.toString());

				OutputStreamWriter outStream = new OutputStreamWriter(
						conn.getOutputStream(), "UTF-8");
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();

				InputStreamReader inputStream = new InputStreamReader(
						conn.getInputStream(), "UTF-8");
				br = new BufferedReader(inputStream);

				String line;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}

				br.close();

				pString = builder.toString();
				Log.d("pString in read comment", pString);

				JSONObject jObject = new JSONObject(pString);
				JSONArray c_userObject = new JSONArray(
						jObject.getString("user_id"));
				JSONArray c_commentObject = new JSONArray(
						jObject.getString("comment"));
				JSONArray c_idObject = new JSONArray(
						jObject.getString("comment_id"));

				for (int i = 0; i < c_userObject.length(); i++) {
					c_userArray.add(c_userObject.getString(i));
					c_commentArray.add(c_commentObject.getString(i));
					c_idArray.add(c_idObject.getString(i));
				}

			} else {

				throw new Exception("network error");
			}

		} catch (SocketTimeoutException se) {

			result[1] = "network error";

		} catch (Exception e) {

			result[1] = e.getMessage();

		} finally {

			if (conn != null)
				conn.disconnect();

			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
			}
		}
		return result;
	}

	public class CommentReadAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			comment_read(ReadPostActivity.this);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			adapter = new CommentAdapter(ReadPostActivity.this,
					R.layout.commenttext, c_userArray, c_commentArray,
					c_idArray, c_userArray.size(), userID);

			list = (ListView) findViewById(R.id.commentlist);
			list.setAdapter(adapter);

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	protected String[] comment_write(Context context, String location_id) {
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		String[] result = new String[2];
		result[0] = "error"; // JSON flag
		result[1] = null; // message

		try {
			StringBuilder builder = new StringBuilder();

			URL url = new URL("http://54.199.194.197/insert_comment.php");
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				conn.setConnectTimeout(150000); 
				conn.setReadTimeout(150000);
				conn.setDefaultUseCaches(false); 
				conn.setDoInput(true); 
				conn.setDoOutput(true); 
				conn.setRequestMethod("POST"); 
				conn.setRequestProperty("content-type",
						"application/x-www-form-urlencoded"); 
																
				StringBuffer buffer = new StringBuffer();
				buffer.append("user_id").append("=").append(userID).append("&");
				buffer.append("board_id").append("=").append(board_id)
						.append("&");
				buffer.append("comment").append("=")
						.append(txtComment.getText().toString());
				Log.d("text", txtComment.getText().toString());

				OutputStreamWriter outStream = new OutputStreamWriter(
						conn.getOutputStream(), "UTF-8");
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();

				InputStreamReader inputStream = new InputStreamReader(
						conn.getInputStream(), "UTF-8");
				br = new BufferedReader(inputStream);

				String line;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}

				br.close();

				pString = builder.toString();

			} else {

				throw new Exception("network error");
			}

		} catch (SocketTimeoutException se) {

			result[1] = "network error";

		} catch (Exception e) {

			result[1] = e.getMessage();

		} finally {

			if (conn != null)
				conn.disconnect();

			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
			}
		}
		return result;
	}

	public class CommentWriteAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			comment_write(ReadPostActivity.this, "0");
			return null;
		}

		@Override
		protected void onPostExecute(String result) {

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
	
	public class deleteBoardAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			delete_board();
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "게시물이 삭제되었습니다.", Toast.LENGTH_SHORT).show();
			   mIntent = new Intent(ReadPostActivity.this, MainActivity.class);
		       mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		       mIntent.putExtra("userID", userID);
		       startActivity(mIntent);
			   super.onPostExecute(result);
			super.onPostExecute(result);
		}
		
	}

	public void clear() {
		c_userArray.clear();
		c_commentArray.clear();
		c_idArray.clear();
	}

	protected String[] delete_board() {
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		String[] result = new String[2];
		result[0] = "error"; // JSON flag
		result[1] = null; // message

		try {
			StringBuilder builder = new StringBuilder();

			URL url = new URL("http://54.199.194.197/delete_board.php");
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				conn.setConnectTimeout(150000); 
				conn.setReadTimeout(150000);
				conn.setDefaultUseCaches(false); 
				conn.setDoInput(true); 
				conn.setDoOutput(true);
				conn.setRequestMethod("POST"); 
				conn.setRequestProperty("content-type",
						"application/x-www-form-urlencoded"); 

				StringBuffer buffer = new StringBuffer();
				buffer.append("board_id").append("=").append(board_id);

				OutputStreamWriter outStream = new OutputStreamWriter(
						conn.getOutputStream(), "UTF-8");
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();

				InputStreamReader inputStream = new InputStreamReader(
						conn.getInputStream(), "UTF-8");
				br = new BufferedReader(inputStream);

				String line;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}

				br.close();

				pString = builder.toString();

			} else {

				throw new Exception("network error");
			}

		} catch (SocketTimeoutException se) {

			result[1] = "network error";

		} catch (Exception e) {

			result[1] = e.getMessage();

		} finally {

			if (conn != null)
				conn.disconnect();

			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
			}
		}
		return result;
	}
	
	protected String[] like_post(Context context) {
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		String[] result = new String[2];
		result[0] = "error"; // JSON flag
		result[1] = null; // message

		try {
			StringBuilder builder = new StringBuilder();

			URL url = new URL("http://54.199.194.197/add_like.php");
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				conn.setConnectTimeout(150000); 
				conn.setReadTimeout(150000);
				conn.setDefaultUseCaches(false); 
				conn.setDoInput(true); 
				conn.setDoOutput(true); 
				conn.setRequestMethod("POST");
				conn.setRequestProperty("content-type",
						"application/x-www-form-urlencoded"); 
																
				StringBuffer buffer = new StringBuffer();
				buffer.append("user_id").append("=").append(userID).append("&");
				buffer.append("board_id").append("=").append(board_id);

				OutputStreamWriter outStream = new OutputStreamWriter(
						conn.getOutputStream(), "UTF-8");
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();

				InputStreamReader inputStream = new InputStreamReader(
						conn.getInputStream(), "UTF-8");
				br = new BufferedReader(inputStream);

				String line;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}

				br.close();

				pString = builder.toString();

			} else {

				throw new Exception("network error");
			}

		} catch (SocketTimeoutException se) {

			result[1] = "network error";

		} catch (Exception e) {

			result[1] = e.getMessage();

		} finally {

			if (conn != null)
				conn.disconnect();

			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
			}
		}
		return result;
	}

	public class LikePostAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			like_post(ReadPostActivity.this);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	protected String[] unlike_post(Context context) {
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		String[] result = new String[2];
		result[0] = "error"; // JSON flag
		result[1] = null; // message

		try {
			StringBuilder builder = new StringBuilder();

			URL url = new URL("http://54.199.194.197/remove_like.php");
			conn = (HttpURLConnection) url.openConnection();

			if (conn != null) {
				conn.setConnectTimeout(150000); 
				conn.setReadTimeout(150000);
				conn.setDefaultUseCaches(false);
				conn.setDoInput(true); 
				conn.setDoOutput(true); 
				conn.setRequestMethod("POST");
				conn.setRequestProperty("content-type",
						"application/x-www-form-urlencoded"); 
				StringBuffer buffer = new StringBuffer();
				buffer.append("user_id").append("=").append(userID).append("&");
				buffer.append("board_id").append("=").append(board_id);

				OutputStreamWriter outStream = new OutputStreamWriter(
						conn.getOutputStream(), "UTF-8");
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();

				InputStreamReader inputStream = new InputStreamReader(
						conn.getInputStream(), "UTF-8");
				br = new BufferedReader(inputStream);

				String line;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}

				br.close();

				pString = builder.toString();

			} else {

				throw new Exception("network error");
			}

		} catch (SocketTimeoutException se) {

			result[1] = "network error";

		} catch (Exception e) {

			result[1] = e.getMessage();

		} finally {

			if (conn != null)
				conn.disconnect();

			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
			}
		}
		return result;
	}

	public class UnlikePostAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			unlike_post(ReadPostActivity.this);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		// TODO Auto-generated method stub
		return false;
	}
	
	public class ConfirmLikePostAsync extends AsyncTask<String, String, String> {
		String result;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			result = confirm_like_post(ReadPostActivity.this);
			likeFlag = result;
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			invalidateOptionsMenu();
			waitDialog.dismiss();
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}
	}

	protected String confirm_like_post(Context context){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;

		try{
	  	StringBuilder builder = new StringBuilder();
	  	
	  	URL url = new URL("http://54.199.194.197/boolean_like.php");
	  	conn = (HttpURLConnection)url.openConnection();
	  	
	  	if(conn != null){
	  		conn.setConnectTimeout(5000000);	
	  		conn.setReadTimeout(5000000);
	  		conn.setDefaultUseCaches(false); 
	      	conn.setDoInput(true); 
	      	conn.setDoOutput(true);  
	      	conn.setRequestMethod("POST"); 
	      	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
	         
	    	StringBuffer buffer = new StringBuffer();
	    	buffer.append("user_id").append("=").append(userID).append("&");
	       buffer.append("board_id").append("=").append(board_id);

	       OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	       PrintWriter writer = new PrintWriter(outStream);
	       writer.write(buffer.toString());
	       writer.flush();

	       InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	       br = new BufferedReader(inputStream);
	      
	   	String line;
	   	while((line = br.readLine()) != null){
	   	   builder.append(line);
	   	}
	      
	   	br.close();
	   	
	   	pString =  builder.toString();
	   	
	  	}else{
	  		
	  		throw new Exception("network error");
	  	}
	  	
	  }catch(SocketTimeoutException se){
	  	
	  	
	  }catch(Exception e){
	  	
	  	
	  }finally{
	  	
	  	if(conn != null)
	  		conn.disconnect();

	  	if(br != null){
	  		try {
	  			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
	  	}
	  }
	  return pString;
	}
}
